package controllers

import (
	"cangku/cache"
	"cangku/models"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"io"
	"os"
	"path/filepath"
	"time"
)

type XshuoController struct {
	beego.Controller
}

func (c *XshuoController) Add() {
	name := c.GetString("name")
	Content := c.GetString("content")
	img := c.GetString("img")

	if name == "" || Content == "" || img == "" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "内容不允许为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	xshuo := models.Xshuo{
		Name:    name,
		Content: Content,
		Img:     img,
	}

	if err := xshuo.Create(); err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "系统错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("Xshuo_error_%d", xshuo.ID)
	jsonData, _ := json.Marshal(xshuo)
	cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*24)

	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
		Data: xshuo,
	}
	c.ServeJSON()
	return
}

func (c *XshuoController) Upload() {
	file, m, err := c.GetFile("img")
	if err != nil {
		return
	}
	ext := filepath.Ext(m.Filename)
	if ext != ".jpg" && ext != ".png" && ext != ".jpeg" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "图片格式不正确",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if m.Size > 2*1024*1024 {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "图片大小不能超过2M",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	openfile, err := os.OpenFile("static/img/"+m.Filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0777)
	io.Copy(openfile, file)

	c.Data["json"] = Res{
		Code: 200,
		Msg:  "图片上传成功",
		Data: "http://127.0.0.1:8088/static/img/" + m.Filename,
	}
	c.ServeJSON()
	return
}

func (c *XshuoController) List() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	keyword := c.GetString("keyword")
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")

	var xshuo models.Xshuo
	var list []*models.Xshuo

	key := fmt.Sprintf("xshuo_error_%s_%d", keyword, page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if cacheData == "" {
		list, _ = xshuo.List(keyword, page, pageSize)
		if len(list) != 0 {
			jsonData, _ := json.Marshal(list)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*24)
		}
	} else {
		fmt.Println("获取成功")
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查找成功",
		Data: list,
	}
	c.ServeJSON()
	return
}

func (c *XshuoController) Del() {
	var err error
	id, _ := c.GetInt("id")
	var xshuo models.Xshuo
	xshuo.ID = uint(id)

	if err = xshuo.Get(); err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "系统错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if err = xshuo.Del(); err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "系统错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("Xshuo_Del_%d", xshuo.ID)
	cache.Rdb.Del(cache.Ctx, key)

	c.Data["json"] = Res{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
